package com.dencycheng.redismq.service.impl;

import com.dencycheng.redismq.service.MqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class MqServiceImpl implements MqService {

    private static final String MQ_KEY = "mq";

    /**
     * 阻塞60秒
     */
    private static final Integer BLOCK_TIME = 60;


    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void send(String msg) {
        redisTemplate.opsForList().leftPush(MQ_KEY, msg);
    }

    @Override
    public void listener() {
        RedisConnection connection = null;
        try {
            connection = redisTemplate.getConnectionFactory().getConnection();
            while (true) {
                List<byte[]> data = connection.bRPop(BLOCK_TIME, MQ_KEY.getBytes(StandardCharsets.UTF_8));
                if(null != data){
                    System.out.println(new String(data.get(1)));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connection) {
                connection.close();
            }
        }
    }
}
